<?php
/***************************************************************************
   Coppermine 1.3.1 for CPG-Dragonfly™
  **************************************************************************
   Port Copyright (c) 2004-2005 CPG Dev Team
   http://dragonflycms.com/
  **************************************************************************
   v1.1 (c) by Grégory Demar http://coppermine.sf.net/
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
****************************************************************************/
if (!defined('CPG_NUKE')) { die("You can't access this file directly..."); }

require("modules/" . $module_name . "/include/load.inc");

if (!GALLERY_ADMIN_MODE) {
	return cpg_die(_ERROR, ACCESS_DENIED);
}

abstract class Coppermine_CatMgr
{

	public static function getSelectBox($highlight = 0, $curr_cat)
	{
		global $CAT_LIST;
		$lb = '<select name="parent">
			<option value="0"' . ($highlight == 0 ? ' selected="selected"': '') . ">* No Category *</option>\n";
		foreach ($CAT_LIST as $category) {
			if ($category['cid'] != 1 && $category['cid'] != $curr_cat) {
				$lb .= '<option value="' . $category['cid'] . '"' . ($highlight == $category['cid'] ? ' selected="selected"': '') . ">" . $category['name'] . "</option>\n";
			}
		}
		return $lb . '</select>';
	}

	public static function getCategories($parent=0)
	{
		global $CONFIG, $db;
		$parent = intval($parent);
		$items  = array();
		$result = $db->query("SELECT cid id, catname name FROM {$CONFIG['TABLE_CATEGORIES']} WHERE parent = {$parent} ORDER BY pos");
		foreach ($result as $cat) {
			$cat['children'] = self::getCategories($cat['id']);
			$items[] = $cat;
		}
		return $items;
	}


}

// Fix categories that have an invalid parent
function fix_cat_table()
{
	global $CONFIG, $db;
	$result = $db->query("SELECT cid FROM {$CONFIG['TABLE_CATEGORIES']}");
	if ($result->num_rows) {
		$set = array();
		while ($row = $result->fetch_row()) { $set[] = $row[0]; }
		$db->exec('UPDATE '.$CONFIG['TABLE_CATEGORIES'].' SET parent = 0 WHERE parent=cid OR parent NOT IN ('.implode(',',$set).')');
	}
}

function get_subcat_data($parent, $ident = '')
{
	global $CONFIG, $CAT_LIST, $db;
	$parent = intval($parent);
	if (!$parent) { $CAT_LIST = array(); }
	$result = $db->query("SELECT cid, catname name, parent FROM {$CONFIG['TABLE_CATEGORIES']} WHERE parent = {$parent} ORDER BY pos");
	$prev_cid = $last_index = 0;
	foreach ($result as $pos => $subcat) {
		$subcat['pos']  = $pos;
		$subcat['last'] = $pos==$result->num_rows-1;
		$subcat['name'] = $ident . $subcat['name'];
		if ($pos > 0) {
			$subcat['prev']  = $prev_cid;
			$CAT_LIST[count($CAT_LIST)-1]['next'] = $subcat['cid'];
		}
		$CAT_LIST[] = $subcat;
		$prev_cid   = $subcat['cid'];
		get_subcat_data($subcat['cid'], $ident . '&nbsp;&nbsp;&nbsp;');
	}
}

function update_cat_order()
{
	global $CAT_LIST, $CONFIG, $db;
	foreach ($CAT_LIST as $category) {
		$db->exec("UPDATE {$CONFIG['TABLE_CATEGORIES']} SET pos={$category['pos']} WHERE cid = {$category['cid']}");
	}
}

if ('POST' === $_SERVER['REQUEST_METHOD'])
{

	if (isset($_POST['move_item'])) {
		$cid = $_POST->uint('move_item');
		$cat = $db->uFetchAssoc("SELECT pos, parent FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid={$cid}");
		if (!$cat) return cpg_die(_ERROR, UNKNOWN_CAT);

		$db->exec("UPDATE {$CONFIG['TABLE_CATEGORIES']} SET pos=pos-1 WHERE pos>{$cat['pos']} AND parent={$cat['parent']}");

		$pid = $_POST->uint('parent_id');
		$aid = $_POST->uint('after_id');
		$pos = -1;
		if ($aid) {
			$p = $db->uFetchRow("SELECT pos, parent FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid={$aid}");
			if ($p) {
				$pos = $p[0];
				$pid = $p[1];
			}
		}
		$db->exec("UPDATE {$CONFIG['TABLE_CATEGORIES']} SET pos=pos+1 WHERE pos>{$pos} AND parent={$pid}");

		++$pos;
		$db->exec("UPDATE {$CONFIG['TABLE_CATEGORIES']} SET pos={$pos}, parent={$pid} WHERE cid={$cid}");

		fix_cat_table();
		update_cat_order();

		header('Content-Type: application/json');
		exit(json_encode(array('moved'=>true)));
	}

	if (isset($_GET['delete']) && isset($_POST['confirm'])) {
		$cid = $_GET->uint('cid');
		if (1 == $cid) return cpg_die(_ERROR, USERGAL_CAT_RO);
		$cat = $db->uFetchRow("SELECT parent FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid = {$cid}");
		if (!$cat) return cpg_die(_ERROR, UNKNOWN_CAT);
		list($parent) = $cat[0];
		$db->exec("UPDATE {$CONFIG['TABLE_CATEGORIES']} SET parent={$parent} WHERE parent = {$cid}");
		$db->exec("UPDATE {$CONFIG['TABLE_ALBUMS']} SET category={$parent} WHERE category = {$cid}");
		$db->exec("DELETE FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid={$cid}");

		fix_cat_table();
		update_cat_order();
	}

	switch ($_POST->raw('oppe'))
	{
		case 'savecat':
			$cid = $_POST->uint('cid');
			if (!isset($_POST['parent'], $_POST['catname'], $_POST['description'])) {
				return cpg_die(_CRITICAL_ERROR, sprintf(MISS_PARAM, 'savecat'));
			}
			$parent = $_POST->uint('parent');
			$catname = Fix_Quotes($_POST['catname']) ?: '&lt;???&gt;';
			$description = Fix_Quotes($_POST['description']);
			if ($cid) {
				$db->exec("UPDATE {$CONFIG['TABLE_CATEGORIES']} SET parent={$parent}, catname='{$catname}', description='{$description}' WHERE cid = {$cid}");
			} else {
				$db->exec("INSERT INTO {$CONFIG['TABLE_CATEGORIES']} (pos, parent, catname, description) VALUES (10000, {$parent}, '{$catname}', '{$description}')");
			}
			fix_cat_table();
			update_cat_order();
			break;
	}
	URL::redirect(URL::index("&file=catmgr"));
}

get_subcat_data(0);

$OUT = Dragonfly::getKernel()->OUT;

if (isset($_GET['edit'])) {
	$cid = $_GET->uint('edit');
	if (!$cid) { return cpg_die(_CRITICAL_ERROR, UNKNOWN_CAT); }
	$current_category = $db->uFetchAssoc("SELECT cid, catname name, parent, description FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid = {$cid}");
	if (!$current_category) return cpg_die(_ERROR, UNKNOWN_CAT);
}

else if (isset($_GET['delete'])) {
	$cid = $_GET->uint('delete');
	if (1 == $cid) return cpg_die(_ERROR, USERGAL_CAT_RO);
	$cat = $db->uFetchRow("SELECT catname FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid = {$cid}");
	if (!$cat) return cpg_die(_ERROR, UNKNOWN_CAT);
	cpg_delete_msg(URL::index("&amp;file=catmgr&amp;delete={$cid}"), CONFIRM_DELETE_CAT.': '.$cat[0]);
}

else {
	//define('META_LNK','&cat=0');
	Dragonfly_Output_Css::add('poodle/tree');
	Dragonfly_Output_Js::add('includes/javascript/poodle.js');
//	Dragonfly_Output_Js::add('includes/poodle/javascript/tree.js');
	Dragonfly_Output_Js::add('modules/coppermine/javascript/catmgr.js');
	$OUT->catlist = $CAT_LIST;
	$current_category = array('cid' => 0, 'parent' => 0, 'name' => '', 'description' => '');
}

pageheader(MANAGE_CAT);
$OUT->catselect = Coppermine_CatMgr::getSelectBox($current_category['parent'], $current_category['cid']);
$OUT->category  = $current_category;
$OUT->display('coppermine/catmgr');

pagefooter();
